package cn.chenhuanming.shh.administer.intermediary.business.eventHandler;

import cn.chenhuanming.shh.administer.entity.jpa.UserSystem;
import cn.chenhuanming.shh.administer.exception.ResourceExistedException;
import cn.chenhuanming.shh.administer.repository.UserSystemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;

/**
 * Created by chenhuanming on 2017-08-22.
 *
 * @author chenhuanming
 */
@Component
@RepositoryEventHandler
public class UserSystemEventHandler {

    @Autowired
    UserSystemRepository userSystemRepository;

    @HandleBeforeCreate
    public void beforeCreate(UserSystem userSystem){
        if(userSystemRepository.exists(userSystem.getUsername()))
            throw new ResourceExistedException();
        if(userSystem.getUserRole()==null)
            throw new IllegalArgumentException("角色不能为空!");
        userSystem.setRoleName(userSystem.getUserRole().getName());
    }
}
